package cn.newstrength.lijingyu.step;

import cn.newstrength.wtdf.plugin.service.RedisService;
import cn.newstrength.wtdf.plugin.util.TranUtils;
import cn.newstrength.wtdf.web.databus.DataContext;
import cn.newstrength.wtdf.web.processor.Operation;
import cn.newstrength.wtdf.web.processor.OperationStep;
import cn.newstrength.lijingyu.data.LijySampleObj;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

public class LijyRedisSampleStep implements OperationStep {
	private final static Logger logger = LoggerFactory.getLogger(LijyRedisSampleStep.class);
	@Override
	public int excute(Operation oper) {
		/*
		 * 数据预处理
		 */
		DataContext dc = oper.getContext();
		String key = dc.getElementValue("key");
		/*
		 * 获取 Redis 服务
		 */
		RedisService redisService = oper.getBean("redisService", RedisService.class);
		/*
		 * 存储字符串
		 */
		redisService.put("cn:newstrength:nsms.sample.string", "Hi redis!",30);
		logger.info("Redis value：{}",TranUtils.toJson(redisService.get("cn:newstrength:nsms.sample.string")));
		/*
		 * 存储对象
		 */
		LijySampleObj sampleObj = new LijySampleObj();
		sampleObj.setId(1);
		sampleObj.setName("王新栋");
		sampleObj.setGender("1");
		sampleObj.setPassword("changeit");
		sampleObj.setAge(40);
		redisService.put("cn:newstrength:nsms.sample.bean", sampleObj,30);//30秒后删除
		Object value = redisService.get("cn:newstrength:nsms.sample.bean");
		logger.info("Redis value：{}",TranUtils.toJson(value));
		/*
		 * 存储文件
		 */
		File file = new File("c:/Windows/system.ini");
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(file);
			byte[] array = IOUtils.toByteArray(fs);
			redisService.put("cn:newstrength:nsms.sample.file", array,30);//30秒后删除
		} catch (Exception e) {
			logger.error("文件不存在");
		} finally {
			IOUtils.closeQuietly(fs);
		}
		/*
		 * 回传数据
		 */
		dc.setTranStepResult("存储字符串、SampleObj对象，File对象成功，请查看节点 cn:newstrength:nsms.sample （TTL 30S）");
		return 0;
	}

	@Override
	public int init(Map<String, String> arg0) {
		return 0;
	}
}
